import os
import tkinter as tk
from tkinter import messagebox
from tkinter import PhotoImage

from scrapy.cmdline import execute

# 打开搜索界面
def open_search_interface():
    # 关闭初始界面
    root.withdraw()
    # 打开搜索界面
    search_window.deiconify()

# 执行爬虫并且展示
def show_wordcloud():
    # 获取搜索输入
    Movie_name = entry.get("1.0", tk.END).strip()
    if not Movie_name:
        # 如果搜索输入为空，弹出提示窗口
        messagebox.showinfo("提示", "请正确输入搜索内容")
        return
    os.environ['MOVIE_NAME'] = Movie_name  # 将电影名称传入环境变量之中
    execute('scrapy crawl douban'.split())  # 到这里进入到scrapy框架中

# 创建主窗口
root = tk.Tk()
root.title("电影词云生成器")

# 计算窗口居中位置
window_width = 400
window_height = 300
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width - window_width) // 2
y = (screen_height - window_height) // 2
root.geometry(f"{window_width}x{window_height}+{x}+{y}")

# 设置窗口图标
icon = PhotoImage(file='icon.png')  # 请确保icon.png文件存在
root.iconphoto(True, icon)

# 设置窗口背景颜色
root.configure(bg='#f0f0f0')

# 创建欢迎标签
welcome_label = tk.Label(root, text="生成影评词云", font=("Helvetica", 18, 'bold'), bg='#f0f0f0')
welcome_label.pack(pady=(70, 10))

# 创建开始按钮
start_button = tk.Button(root, text="启动程序", command=open_search_interface, font=("Helvetica", 14), bg='#4CAF50', fg='white')
start_button.pack(pady=(90, 10))

# 创建搜索界面
search_x = (screen_width - 400) // 2
search_y = (screen_height - 400) // 2
search_window = tk.Toplevel()
search_window.title("影评词云生成")
search_window.geometry(f"400x400+{search_x}+{search_y}")
search_window.protocol("WM_DELETE_WINDOW", root.quit)  # 关闭搜索窗口时退出程序
search_window.withdraw()  # 初始时隐藏搜索窗口
search_window.configure(bg='#f0f0f0')

# 添加提示标签
prompt_label = tk.Label(search_window, text="请输入影名:", font=("Helvetica", 20, 'bold'), bg='#f0f0f0')
prompt_label.pack(pady=(90, 10))

# 在搜索界面上创建搜索框和按钮
entry = tk.Text(search_window, width=30)
entry.pack(pady=(20, 10))
entry.place(x=80,y=180)
entry.config(borderwidth=2, relief="sunken",height=2)
# 搜索按钮负责启动爬虫并生成词云
search_icon = PhotoImage(file='search_icon.png') 
search_icon = search_icon.subsample(8, 8)
search_button = tk.Button(search_window, command=show_wordcloud, width=30, bg='#2196F3', fg='white',compound=tk.LEFT,image=search_icon)
search_button.pack(pady=(10, 10))
search_button.place(x=310, y=180)

# 运行主事件循环
root.mainloop()
